#include "web_socket_server.h"
#include "backend_service.h"
#include "command/command_executor.h"
#include "database/database_manager.h"
#include <QDebug>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QAbstractSocket>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUuid>
#include <QDateTime>

WebSocketServer::WebSocketServer(QObject *parent)
    : QObject(parent)
    , m_webSocketServer(nullptr)
    , m_backendService(nullptr)
    , m_commandExecutor(new CommandExecutor(this))
{
}

WebSocketServer::~WebSocketServer()
{
    stopServer();
}

bool WebSocketServer::startServer(quint16 port)
{
    // 如果服务器已经在运行，先停止
    if (m_webSocketServer && m_webSocketServer->isListening()) {
        stopServer();
    }
    
    // 创建 WebSocket 服务器
    m_webSocketServer = new QWebSocketServer(
        QStringLiteral("WebSocket Server"),
        QWebSocketServer::NonSecureMode,
        this
    );
    
    // 连接信号槽
    connect(m_webSocketServer, &QWebSocketServer::newConnection,
            this, &WebSocketServer::onNewConnection);
    
    // 连接服务器错误信号
    connect(m_webSocketServer, &QWebSocketServer::acceptError,
            this, &WebSocketServer::onServerError);
    
    // 开始监听
    if (m_webSocketServer->listen(QHostAddress::Any, port)) {
        qDebug() << "WebSocket 服务器已启动，监听端口:" << port;
        qDebug() << "服务器地址: ws://" << QHostAddress(QHostAddress::LocalHost).toString() << ":" << port;
        
        // 显示所有可用的IP地址
        QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
        for (const QHostAddress &address : addresses) {
            if (address.protocol() == QAbstractSocket::IPv4Protocol && !address.isLoopback()) {
                qDebug() << "服务器也可通过以下地址访问: ws://" << address.toString() << ":" << port;
            }
        }
        
        emit serverStarted(port);
        return true;
    } else {
        QString errorString = QString("WebSocket 服务器启动失败: %1").arg(m_webSocketServer->errorString());
        qDebug() << errorString;
        emit errorOccurred(errorString);
        return false;
    }
}

void WebSocketServer::stopServer()
{
    if (m_webSocketServer) {
        // 断开所有客户端连接
        for (QWebSocket *client : m_clients) {
            if (client) {
                client->close();
                client->deleteLater();
            }
        }
        m_clients.clear();
        
        // 停止服务器
        if (m_webSocketServer->isListening()) {
            m_webSocketServer->close();
            qDebug() << "WebSocket 服务器已停止";
        }
        
        m_webSocketServer->deleteLater();
        m_webSocketServer = nullptr;
        
        emit serverStopped();
    }
}

bool WebSocketServer::isRunning() const
{
    return m_webSocketServer && m_webSocketServer->isListening();
}

void WebSocketServer::broadcastMessage(const QString &message)
{
    if (!isRunning()) {
        qDebug() << "WebSocket 服务器未运行，无法广播消息";
        return;
    }
    
    QByteArray data = message.toUtf8();
    int sentCount = 0;
    
    for (QWebSocket *client : m_clients) {
        if (client && client->state() == QAbstractSocket::ConnectedState) {
            client->sendTextMessage(message);
            sentCount++;
        }
    }
    
    qDebug() << QString("广播消息给 %1 个客户端: %2").arg(sentCount).arg(message);
}

void WebSocketServer::sendMessageToClient(const QString &clientId, const QString &message)
{
    QWebSocket *client = findClient(clientId);
    if (client && client->state() == QAbstractSocket::ConnectedState) {
        client->sendTextMessage(message);
        qDebug() << QString("发送消息给客户端 %1: %2").arg(clientId, message);
    } else {
        qDebug() << QString("客户端 %1 未找到或未连接").arg(clientId);
    }
}

void WebSocketServer::onNewConnection()
{
    if (!m_webSocketServer) {
        return;
    }
    
    QWebSocket *socket = m_webSocketServer->nextPendingConnection();
    if (!socket) {
        return;
    }
    
    QString clientId = generateClientId(socket);
    
    // 连接信号槽
    connect(socket, &QWebSocket::textMessageReceived,
            this, &WebSocketServer::onTextMessageReceived);
    connect(socket, &QWebSocket::binaryMessageReceived,
            this, &WebSocketServer::onBinaryMessageReceived);
    connect(socket, &QWebSocket::disconnected,
            this, &WebSocketServer::onSocketDisconnected);
    
    // 添加到客户端列表
    m_clients.append(socket);
    
    qDebug() << QString("新客户端连接: %1 (IP: %2, 总连接数: %3)")
                .arg(clientId)
                .arg(socket->peerAddress().toString())
                .arg(m_clients.size());
    
    emit clientConnected(clientId);
}

void WebSocketServer::onTextMessageReceived(const QString &message)
{
    QWebSocket *socket = qobject_cast<QWebSocket*>(sender());
    if (!socket) {
        return;
    }
    
    QString clientId = getClientId(socket);
    
    qDebug() << QString("收到来自客户端 %1 的文本消息: %2")
                .arg(clientId, message);
    
    // 尝试解析 JSON 命令
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(message.toUtf8(), &parseError);
    
    if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
        QJsonObject jsonObj = jsonDoc.object();
        QString command = jsonObj.value("command").toString();
        
        // 暂时只为 openurlfile创建 command
        if (command == "openurlfile") {
            // 使用 CommandExecutor 执行命令
            if (m_commandExecutor) {
                m_commandExecutor->executeOpenUrlFileCommand(jsonObj);
            } else {
                qDebug() << "CommandExecutor 未初始化，无法执行命令";
            }
        }
    }
    
    emit messageReceived(clientId, message);
}

void WebSocketServer::onBinaryMessageReceived(const QByteArray &message)
{
    QWebSocket *socket = qobject_cast<QWebSocket*>(sender());
    if (!socket) {
        return;
    }
    
    QString clientId = getClientId(socket);
    
    qDebug() << QString("收到来自客户端 %1 的二进制消息，大小: %2 字节")
                .arg(clientId)
                .arg(message.size());
    
    // 可以将二进制消息转换为文本消息信号
    emit messageReceived(clientId, QString::fromUtf8(message));
}

void WebSocketServer::onSocketDisconnected()
{
    QWebSocket *socket = qobject_cast<QWebSocket*>(sender());
    if (!socket) {
        return;
    }
    
    QString clientId = getClientId(socket);
    
    // 从客户端列表中移除
    m_clients.removeAll(socket);
    
    qDebug() << QString("客户端断开连接: %1 (剩余连接数: %2)")
                .arg(clientId)
                .arg(m_clients.size());
    
    emit clientDisconnected(clientId);
    
    // 清理套接字
    socket->deleteLater();
}

void WebSocketServer::onServerError()
{
    if (m_webSocketServer) {
        QString errorString = QString("WebSocket 服务器错误: %1")
                                .arg(m_webSocketServer->errorString());
        qDebug() << errorString;
        emit errorOccurred(errorString);
    }
}

QString WebSocketServer::generateClientId(QWebSocket *socket)
{
    if (!socket) {
        return QString();
    }
    
    // 使用 IP 地址和端口组合作为客户端ID
    return QString("%1:%2")
           .arg(socket->peerAddress().toString())
           .arg(socket->peerPort());
}

QString WebSocketServer::getClientId(QWebSocket *socket)
{
    return generateClientId(socket);
}

QWebSocket* WebSocketServer::findClient(const QString &clientId)
{
    for (QWebSocket *client : m_clients) {
        if (client && getClientId(client) == clientId) {
            return client;
        }
    }
    return nullptr;
}

void WebSocketServer::setBackendService(BackendService *backendService)
{
    m_backendService = backendService;
    
    // 设置 CommandExecutor 的 BackendService 和 DatabaseManager
    if (m_commandExecutor && m_backendService) {
        m_commandExecutor->setBackendService(m_backendService);
        DatabaseManager *databaseManager = m_backendService->getDatabaseManager();
        if (databaseManager) {
            m_commandExecutor->setDatabaseManager(databaseManager);
        }
    }
}

